package com.slz3.business.frame.steward;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.slz3.business.frame.util.BeanMapUtils;
import com.slz3.business.frame.util.FromSourceIntoTarget;
import com.slz3.business.frame.util.GenerateNumber;
import org.springframework.web.reactive.function.server.ServerRequest;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.lang.reflect.ParameterizedType;
import java.util.Map;
import java.util.Set;

/**
 * 所有现成安全的缓存应该放在这里集中统一管理
 */
public class Steward {

    // #####                                        #####
    // #####                    Json                #####
    // #####                                        #####

    private static final ObjectMapper mapper = new ObjectMapper();

    public static byte[] writeValueAsBytes(Object object) throws JsonProcessingException {
        return mapper.writeValueAsBytes(object);
    }

    // #####                                        #####
    // #####             HibernateValidator         #####
    // #####                                        #####

    private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
        return validator.validate(object, groups);
    }

    public static <T> void constraintViolations(ServerRequest req, T temStyle1, Class<?>... groups) {
        HibernateValidatorSteward.constraintViolations(req, validate(temStyle1, groups));
    }

    // #####                                        #####
    // #####            FromSourceIntoTarget        #####
    // #####                                        #####

    public static void merge(Object source, Object target) {
        FromSourceIntoTarget.merge(source, target);
    }

    public static Map<String,Object> obj2Map(Object obj){
        return BeanMapUtils.object2Map(obj);
    }

    public static void map2Obj(Map<String,Object> map,Object obj){
        BeanMapUtils.convert(map, obj);
    }

    public  static  String toJson(Object obj) {
        return  new Gson().toJson(obj);
    }

    public static void initNullField(Object obj) {
        ReflectBeanPropertiesSteward.initNullField(obj);
    }

    public static String genNum(String firstCode) {
        return GenerateNumber.generateNumber(firstCode);
    }

    public static Object getTClass(Class clazz) {
        return ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments()[0];
    }

}